// Prevents additional console window on Windows in release, DO NOT REMOVE!!   https://www.shuttle.dev/blog/2023/12/08/clap-rust
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]

use core_api::{app_handle, app_log, is_process_alive};

use std::io::{self, Write};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;

fn main() {
    let app_name = "edog";
    app_log::config_log(app_name);

    let args: Vec<String> = std::env::args().skip(1).collect();
    log::info!("edog: {:?}", &args);

    let bwexam_pid = if let [bwexam_pid_s, ..] = &args[..] {
        // p1: d:\output1.mkv, p2: 薛1, p3: false
        log::info!(
            "bwexam_pid: {}",
            bwexam_pid_s //主进程 PID
        );
        bwexam_pid_s.parse::<u32>().unwrap()
    } else {
        0u32
    };

    match app_handle::get_app_handle(app_name) {
        Err(err) => {
            log::info!("{}", err);
            std::process::exit(-1);
        }

        Ok(handle) => {
            // 设置 Ctrl+C 信号监听
            let running = Arc::new(AtomicBool::new(true));
            let r = running.clone();

            ctrlc::set_handler(move || {
                log::info!("recive ctr+c...");
                edog_lib::stop_keyboard_hook(); // 你的清理函数
                r.store(false, Ordering::SeqCst);
                //当持有该互斥体的最后一个进程退出时，操作系统会自动销毁该对象
                std::process::exit(0);
            })
            .expect("set Ctrl+C handler error");

            std::panic::set_hook(Box::new(|panic_info| {
                log::error!("panic: {:?}", panic_info);
                edog_lib::stop_keyboard_hook();
            }));

            while running.load(Ordering::SeqCst) {
                print!("> ");
                io::stdout().flush().unwrap();

                let mut buf = String::new();
                if io::stdin().read_line(&mut buf).is_err() {
                    log::error!("read stdin error");
                    continue;
                }

                let line = buf.trim().to_lowercase();

                match line.as_str() {
                    "start" => {
                        log::info!("recive start");

                        let _stop_thread = std::thread::spawn(move || {
                            while is_process_alive(bwexam_pid) {
                                // 如果主进程存在
                                std::thread::sleep(std::time::Duration::from_secs(3));
                            }

                            log::info!(
                                "=====edog  is exit,because  bwexam_pid={} is exit",
                                bwexam_pid
                            );
                            edog_lib::stop_keyboard_hook();
                            std::process::exit(-1);
                        });

                        edog_lib::start_keyboard_hook();
                    }
                    "stop" => {
                        log::info!("recive stop");
                        edog_lib::stop_keyboard_hook();
                        break;
                    }
                    _ => {
                        //log::warn!("invalid: '{}'", line);
                    }
                }
            }
            app_handle::close_app_handle(handle);
            log::info!("{} exit", app_name);
        }
    }
}
